function showData() {
    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/get.do",
        data: {type: type, messageNo: id, instance: DepotName},
        dataType: "json",
        success: function(souData) {
            //souData = $.parseJSON(souData);
            var policy_desc = souData.Comment;
            $(".policy_desc").val(policy_desc);
            var data = souData.Content;
            $(".Bind_Action").val(data.Bind_Action);
            $(".UserType").val(data.UserType);
            if (data.UserType == 0) {
                $(".UserName").attr("disabled", true);
            }
            $(".UserName").val(data.UserName);
            for (var i in data.Messages.Message) {
                addNode(trsMessageType(data.Messages.Message[i].MessageType), data.Messages.Message[i].MessageTypes, data.Messages.Message[i].MessageNo)
            }
        }
    });
}
function trMessageType(str) {
    return parseInt(str);
}

function Hex(num) {
    var basechar = 'A'.charCodeAt(0);
    if (num * 1 < 10)
        return num;
    return String.fromCharCode(basechar + (num * 1 - 10));
}
function trsMessageType(str) {
    str = str * 1;
    var bits = Hex(str & 0x0f);
    var ten = Hex(str >> 4);
    return "0x" + ten + bits;
}
function generateParameter() {
    var obj = {};
    obj.Bind_Action = $(".Bind_Action").val();
    obj.UserType = $(".UserType").val();
    if (obj.UserType != "0" || obj.UserType != 0) {
        obj.UserName = $(".UserName").val();
    }
    obj.Messages = {Message: []};
    $(".Messages").each(function() {
        var objs = $(this);
        var Message_Type = trMessageType($(".Message_Type", objs).val());
        var Message_Types = $(".Message_Types", objs).val();
        var Message_No = $(".Message_No", objs).val();
        obj.Messages.Message.push({MessageType: Message_Type, MessageNo: Message_No, MessageTypes: Message_Types});
    });
    obj.MessageNum = obj.Messages.length;
    return obj;
}
//获取所有策略类型
function getPolicyLibrary() {
    var obj;
    $.ajax({
        type: "GET",
        async: false,
        url: "../../assets/data/PolicyLibrary.json",
        data: {},
        dataType: "json",
        success: function(data) {
            obj = data;
        }
    });
    return obj;
}
//获取指定策略类型下的所有策略库
function getLibraryAll(type) {
    var obj;
    $.ajax({
        type: "GET",
        async: false,
        url: "../../policy/get_strategy_all_warehouse",
        data: {MessageType: type},
        dataType: "json",
        success: function(data) {
            obj = data;
        }
    });
    return obj;
}
//获取指定策略库下面的所有策略
function getPolicyAll(type, instance) {
//    console.log("type:" + type);
//    console.log("instance:" + instance);
    var obj;
    $.ajax({
        type: "GET",
        async: false,
        url: "../../action/policy/list.do",
        data: {type: type, instance: base64.encode(instance)},
        dataType: "json",
        success: function(data) {
            obj = data;
        }
    });
    return obj;
}
function addNode(policy_type, instanceName, policy_id) {
    var obj = $(".add");
    var $Messages = $("<div class='control-group Messages'></div>");
    var $label = $("<label class='control-label' for='Message_Type'>策略选项</label>");
    var $controls = $("<div class='controls'></div> ");
    var $message_type = $("<select class='Message_Type' id='Message_Type'></select>");
    for (var i in policyLib) {
        $message_type.append("<option value='" + i + "'>" + policyLib[i] + "</option>");
    }
    var $message_no = $("<select class='Message_Types' id='Message_Types'></select>");
    var $message_nos = $("<select class='Message_No' id='Message_No'></select>");

    $message_type.on("change", function() {
        var policy_type = $(this).val();
        var policyDepot = getLibraryAll(policy_type);
        var $message_no = $(this).next();
        $message_no.html("");
        if (policyDepot.length < 1) {
            $message_no.append("<option value='-1'>无策略库,请先新建策略库</option>")
        } else {
            for (var i in policyDepot) {
                $message_no.append("<option value='" + policyDepot[i].policy_warehouse_name + "'>" + policyDepot[i].policy_warehouse_name + "</option>")
            }
            if (instanceName) {
                $message_no.val(instanceName);
            }
            $message_no.trigger('change');
        }
    });
    $message_no.on("change", function() {
        var policy_type = $(this).prev().val();
        var instanceName = $(this).val();
        var $message_nos = $(this).next();
        var policyList = getPolicyAll(policy_type, instanceName);
        $message_nos.html("");
        if (policyList.length < 1) {
            $message_nos.append("<option value='-1'>无策略,请先新建策略</option>")
        } else {
            for (var i in policyList) {
                $message_nos.append("<option value='" + policyList[i].MessageNo + "'>" + policyList[i].Description + "</option>")
            }
            if (policy_id) {
                $message_nos.val(policy_id);
            }
        }
    })
    var $del = $("<a href='javascript:void(0)' class='btn btn-danger btn-minier' style='margin-left:30px'>&nbsp;删&nbsp;除&nbsp;</a>");
    $del.on("click", function() {
        $(this).parent().parent().remove();
    });
    $controls.append($message_type).append($message_no).append($message_nos).append($del);
    $Messages.append($label).append($controls);
    obj.append($Messages);
    if (policy_type) {
        $message_type.val(policy_type);
    }
    $message_type.trigger('change');
}
function save() {
    var form = $(".form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    var comment = $(".policy_desc").val();
    var policy = generateParameter();
    var Message_flag = true;
    if (policy.Messages.Message.length < 1) {
        alert("请至少添加一类策略!");
        return;
    }
    for (var i in policy.Messages.Message) {
        if (policy.Messages.Message[i].MessageNo == -1) {
            Message_flag = false;
        }
    }
    if (!Message_flag) {
        alert("请确保所有策略选项已选择策略!")
        return;
    }
    policy = JSON.stringify(policy);
    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/create.do",
        data: {comment: comment, policy: policy, type: type, instance: DepotName},
        dataType: "json",
        success: function(data) {
            if (data.result == "true") {
                alert("添加成功！");
                previous();
            } else {
                alert("添加失败!")
            }
        }
    });
}
//编辑数据
function edit() {
    var form = $(".form-horizontal").validate();
    if (!form.form()) {
        return;
    }
    var comment = $(".policy_desc").val();
    var policy = generateParameter();
    var Message_flag = true;
    if (policy.Messages.Message.length < 1) {
        alert("请至少添加一类策略!");
        return;
    }
    for (var i in policy.Messages.Message) {
        if (policy.Messages.Message[i].MessageNo == -1) {
            Message_flag = false;
        }
    }
    if (!Message_flag) {
        alert("请确保所有策略选项已选择策略!")
        return;
    }
    policy = JSON.stringify(policy);
    $.ajax({
        type: "POST",
        async: false,
        url: "../../action/policy/update.do",
        data: {messageNo: id, comment: comment, policy: policy, type: type, instance: DepotName},
        dataType: "json",
        success: function(data) {
            if (data.result == "true") {
                alert("编辑成功！");
                previous();
            } else {
                alert("编辑失败!")
            }
        }
    });
}
//返回上一级
function previous() {
    window.location = "../policyList.html?type=" + type + "&id=" + DepotID + "&name=" + base64.encode(DepotName) + "";
}
//获取url参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}
var base64 = new Base64();
var type = getQueryString("type");
var DepotID = getQueryString("DepotID");
var DepotName = getQueryString("DepotName");
DepotName = base64.decode(DepotName);
var id = getQueryString("id");
var policyLib = getPolicyLibrary();
/*
 * 查看旧版本的策略内容
 */
function show_oldPolicy(array, number) {
    var souData = array[number];
    $(".header").text("当前策略在" + souData.CreateTime + "创建,ID为" + souData.MessageNo + ",版本号为" + souData.MessageSerialNo + ",属于" + souData.Instance + "策略库");

    var policy_desc = souData.Comment;
    $(".policy_desc").val(policy_desc);
    var data = souData.Content;
    $(".Bind_Action").val(data.Bind_Action);
    $(".UserType").val(data.UserType);
    if (data.UserType == 0) {
        $(".UserName").attr("disabled", true);
    }
    $(".UserName").val(data.UserName);
    for (var i in data.Messages.Message) {
        addNode(trsMessageType(data.Messages.Message[i].MessageType), data.Messages.Message[i].MessageTypes, data.Messages.Message[i].MessageNo)
    }
}

/*
 *获取所有版本的策略内容 
 */
function getAllPolicy() {
    $.ajax({
        type: "GET",
        async: false,
        url: "../../action/policy/history_policy_info.do",
        data: {type: type, instance: getQueryString("DepotName"), messageNo: id},
        dataType: "json",
        success: function(data) {
            policyArray = data;
            policyAmount = data.length
        }
    });
}